package cn.tedu.sp02.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.sp01.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * @author 张琪
 * @date 2020/12/18
 * @describe
 */
@Slf4j
@RestController
public class ItemController {

    @Autowired
    private ItemService itemService;

    /**
     * 为了测试集群, 这里注入端口号
     */
    @Value("${server.port}")
    private int port;


    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        log.info("orderId: " + orderId + "port: " + port);

        if (Math.random() < 0.9) {
            int i = new Random().nextInt(5000);
            log.info("延迟: " + i);
            Thread.sleep(i);
        }

        List<Item> items = itemService.getItems(orderId);
        return JsonResult.ok().msg("port = " + port).data(items);
    }

    /**
     * 只处理 POST请求
     * @RequestBody注解, 完整接受POST请求协议体数据
     * @param items
     * @return
     */
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items) {
        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }
}
